#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import json
import os
from check_util import pretty_dict, print_dict, cmp_

reload(sys)
sys.setdefaultencoding("utf-8")


def check_dict(title, f, a, b):
    print>>f, '*** %s ***' % title
    if cmp_(a, b):
        print>>f, 'OK'
        return True
    else:
        print>>f, 'Not OK'
        print>>f, '[ From Crawler ]'
        print_dict(f, a)
        print>>f
        print>>f, '[ From Qi Cha Cha ]'
        print_dict(f, b)
        return False


# 先总体比较, 提取出 a, b 中元素的标识
# 然后取一个在两边都出现过的标识, 输出对应的元素
def check_dict_list(msg, id_, f, a, b):
    print>>f, '*** %s ***' % msg
    ka = []
    kb = []
    for i in a:
        ka.append(i[id_])
    for i in b:
        kb.append(i[id_])
    print>>f, u'总体比较 list 中元素：'
    print>>f, '[ Crawler ]: ', ' '.join(sorted(ka))
    print>>f, '[ QCC     ]: ', ' '.join(sorted(kb))
    print>>f

    print>>f, u'细节比较， 提取 crawler 和 qcc 列表中 %s 字段相同的字典' % id_
    found = False
    for i in ka:
        if i in kb:
            print>>f, '[ Crawler ]: '
            for j in filter(lambda x: x[id_] == i, a):
                print_dict(f, j)
            print>>f, '[ QCC     ]: '
            for j in filter(lambda x: x[id_] == i, b):
                print_dict(f, j)
            found = True
        if found:
            break

    if not found:
        print>>f, u'*** 差异较大 ***'

    return False


def check_one(path, a, b, print_raw=0):
    ret = True
    with open(path, 'w') as f:
        if print_raw:
            print>>f, '*'*5 + ' 打印原始数据' + '*'*5
            pretty_dict(a, header='[ From Crawler  ]')
            pretty_dict(b, header='[ From QiChaCha ]')

        print>>f, u'[ 年报 分析结果 ]'
        ret &= check_dict('[ check baseInfo ]', f, a['baseInfo'], b['baseInfo'])
        ret &= check_dict('[ check website ]', f, a['website'], b['website'])
        ret &= check_dict_list('[ check investorInformations ]', 'shareholderName', f, a['investorInformations'], b['investorInformations'])
        ret &= check_dict('[ check assetsInfo ]', f, a['assetsInfo'], b['assetsInfo'])
        ret &= check_dict_list('[ check equityChangeInformations ]', 'shareholderName', f, a['equityChangeInformations'], b['equityChangeInformations'])
        ret &= check_dict_list('[ check changeRecords ]', 'changedItem', f, a['changeRecords'], b['changeRecords'])
    return ret


def check_year_report_list(key_, la, lb):
    path = u'/'.join(['./result', key_, 'year_report_list_result'])
    if not la and not lb:
        print u'年报为空'
        return True
    if not la or not lb:
        with open(path, 'w') as f:
            if not la:
                print>>f, u'Crawler 获取不了年报, 企查查qpi可以获取'
            if not lb:
                print>>f, u'Crawler 可以获取年报, 企查查qpi获取不了'
                pretty_dict(f, la[0])
        return False

    return check_one(la[0], lb[0], print_raw=4)